package com.luo.backend.controller;

import com.luo.backend.common.ApiResponse;
import com.luo.backend.dto.FoodResponse;
import com.luo.backend.dto.MerchantFoodRequest;
import com.luo.backend.dto.UpdateFoodStatusRequest;
import com.luo.backend.entity.User;
import com.luo.backend.repository.UserRepository;
import com.luo.backend.service.MerchantFoodService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商家菜品管理接口
 */
@RestController
@RequestMapping("/api/v1/merchant/foods")
public class MerchantFoodController {
    
    private static final Logger logger = LoggerFactory.getLogger(MerchantFoodController.class);
    
    @Autowired
    private MerchantFoodService merchantFoodService;
    
    @Autowired
    private UserRepository userRepository;
    
    /**
     * 获取当前登录用户
     */
    private User getCurrentUser(Authentication authentication) {
        Long userId = (Long) authentication.getPrincipal();
        return userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
    }
    
    /**
     * 获取商家菜品列表
     * GET /api/v1/merchant/foods?status=1
     */
    @GetMapping
    public ApiResponse<List<FoodResponse>> getFoods(
            @RequestParam(required = false) Integer status,
            Authentication authentication) {
        try {
            User user = getCurrentUser(authentication);
            
            // 验证是否为商家
            if (!"merchant".equals(user.getRole())) {
                return ApiResponse.error("无权访问");
            }
            
            if (user.getMerchantId() == null) {
                return ApiResponse.error("商家信息不完整");
            }
            
            List<FoodResponse> foods = merchantFoodService.getFoods(user.getMerchantId(), status);
            return ApiResponse.success(foods);
            
        } catch (Exception e) {
            logger.error("获取菜品列表失败", e);
            return ApiResponse.error("获取菜品列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取菜品详情
     * GET /api/v1/merchant/foods/{id}
     */
    @GetMapping("/{id}")
    public ApiResponse<FoodResponse> getFoodDetail(
            @PathVariable Long id,
            Authentication authentication) {
        try {
            User user = getCurrentUser(authentication);
            
            // 验证是否为商家
            if (!"merchant".equals(user.getRole())) {
                return ApiResponse.error("无权访问");
            }
            
            if (user.getMerchantId() == null) {
                return ApiResponse.error("商家信息不完整");
            }
            
            FoodResponse food = merchantFoodService.getFoodDetail(user.getMerchantId(), id);
            return ApiResponse.success(food);
            
        } catch (Exception e) {
            logger.error("获取菜品详情失败", e);
            return ApiResponse.error("获取菜品详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 新增菜品
     * POST /api/v1/merchant/foods
     */
    @PostMapping
    public ApiResponse<FoodResponse> createFood(
            @RequestBody MerchantFoodRequest request,
            Authentication authentication) {
        try {
            User user = getCurrentUser(authentication);
            
            // 验证是否为商家
            if (!"merchant".equals(user.getRole())) {
                return ApiResponse.error("无权访问");
            }
            
            if (user.getMerchantId() == null) {
                return ApiResponse.error("商家信息不完整");
            }
            
            FoodResponse food = merchantFoodService.createFood(user.getMerchantId(), request);
            return ApiResponse.success(food);
            
        } catch (Exception e) {
            logger.error("新增菜品失败", e);
            return ApiResponse.error("新增菜品失败：" + e.getMessage());
        }
    }
    
    /**
     * 修改菜品
     * PUT /api/v1/merchant/foods/{id}
     */
    @PutMapping("/{id}")
    public ApiResponse<FoodResponse> updateFood(
            @PathVariable Long id,
            @RequestBody MerchantFoodRequest request,
            Authentication authentication) {
        try {
            User user = getCurrentUser(authentication);
            
            // 验证是否为商家
            if (!"merchant".equals(user.getRole())) {
                return ApiResponse.error("无权访问");
            }
            
            if (user.getMerchantId() == null) {
                return ApiResponse.error("商家信息不完整");
            }
            
            FoodResponse food = merchantFoodService.updateFood(user.getMerchantId(), id, request);
            return ApiResponse.success(food);
            
        } catch (Exception e) {
            logger.error("修改菜品失败", e);
            return ApiResponse.error("修改菜品失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除菜品
     * DELETE /api/v1/merchant/foods/{id}
     */
    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteFood(
            @PathVariable Long id,
            Authentication authentication) {
        try {
            User user = getCurrentUser(authentication);
            
            // 验证是否为商家
            if (!"merchant".equals(user.getRole())) {
                return ApiResponse.error("无权访问");
            }
            
            if (user.getMerchantId() == null) {
                return ApiResponse.error("商家信息不完整");
            }
            
            merchantFoodService.deleteFood(user.getMerchantId(), id);
            return ApiResponse.success("删除成功");
            
        } catch (Exception e) {
            logger.error("删除菜品失败", e);
            return ApiResponse.error("删除菜品失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新菜品状态（上下架）
     * PUT /api/v1/merchant/foods/{id}/status
     */
    @PutMapping("/{id}/status")
    public ApiResponse<String> updateFoodStatus(
            @PathVariable Long id,
            @RequestBody UpdateFoodStatusRequest request,
            Authentication authentication) {
        try {
            User user = getCurrentUser(authentication);
            
            // 验证是否为商家
            if (!"merchant".equals(user.getRole())) {
                return ApiResponse.error("无权访问");
            }
            
            if (user.getMerchantId() == null) {
                return ApiResponse.error("商家信息不完整");
            }
            
            merchantFoodService.updateFoodStatus(user.getMerchantId(), id, request.getStatus());
            
            String message = request.getStatus() == 1 ? "上架成功" : "下架成功";
            return ApiResponse.success(message);
            
        } catch (Exception e) {
            logger.error("更新菜品状态失败", e);
            return ApiResponse.error("更新菜品状态失败：" + e.getMessage());
        }
    }
}
















